package com.example.petproject.controller;

import com.example.petproject.config.WeChatLoginConfig;
import com.example.petproject.constants.Constants;
import com.example.petproject.entity.model.UmsUser;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.entity.vo.ReturnVO;
import com.example.petproject.service.UmsUserService;
import com.example.petproject.service.third.WeChat.WeChatLoginService;
import com.example.petproject.util.ObjectMapperUtils;
import com.example.petproject.util.PetUmsUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.util.internal.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 包名称：com.example.petproject.controller
 * 类名称：UmsUserControler
 * 类描述：用户控制器
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月06日 09:45
 **/
@RestController
@Tag(name = "用户控制器")
@RequestMapping("/ums/user/")
public class UmsUserController {

    private static final Logger log = LoggerFactory.getLogger(UmsUserController.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UmsUserService umsUserService;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private WeChatLoginService weChatLoginService;

    @PostMapping("/login")
    @Operation(summary = "手机号登录")
    public ReturnVO<?> login(String phone, String sms) {
        //校验验证码是否真确
        //先验证前端传递过来的验证码是否为空
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(sms)) {
            return ReturnVO.error(ReturnStatusEnum.FAIL_PARAM_EMPTY);
        }
        //先生成验证码redis key
        String codeKey = PetUmsUtils.generateSmsRedisKey(Constants.Sms.TYPE_REGISTER_OR_LOGIN, phone);
        String redisCode = stringRedisTemplate.opsForValue().get(codeKey);
        if (!StringUtils.hasText(redisCode) || !sms.equals(redisCode)) {
            //短信验证码已失效
            return ReturnVO.error(ReturnStatusEnum.FAIL_UMS_SMS_CODE_ERROR);
        }
        //判断当前用户是已存在 -- 登录+注册
        //如果当前用户在系统中不存在，则需要新增
        String token = umsUserService.loginOrAdd(phone);
        //生成token,并将基本信息存入Redis，为后续的接口做准备
        if (StringUtils.hasText(token)) {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            return ReturnVO.ok(tokenMap);
        }
        return ReturnVO.error();
    }

    @GetMapping("/getUserByToken")
    @Operation(summary = "获取用户Token")
    public ReturnVO<?> getUserByToken(@RequestHeader(value = "Token") String token) {
        //校验token是否为空
        if (ObjectUtils.isEmpty(token)) {

            return ReturnVO.error(ReturnStatusEnum.AUTH_TOKEN_EMPTY);
        }
        //生成token
        String tokenRedisKey = PetUmsUtils.generateTokenRedisKey(token);
        String userStr = stringRedisTemplate.opsForValue().get(tokenRedisKey);
        if (ObjectUtils.isEmpty(userStr)) {
            return ReturnVO.error(ReturnStatusEnum.AUTH_USER_NOT_LOGIN);
        }
        //将取出的用户，反序列化
        try {
            UmsUser umsUser = ObjectMapperUtils.stringToObj(userStr, UmsUser.class);
            return ReturnVO.ok(umsUser);
        } catch (JsonProcessingException e) {
            log.error("反序列化用户信息失败:{}", e.getMessage());
            return ReturnVO.error(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
    }

    @GetMapping("/weChat/back")
    @Operation(summary = "微信扫码登录")
    public ReturnVO<?> weChatBack(String wxCode) {
        //验证code是否为空
        if (ObjectUtils.isEmpty(wxCode)) {
            log.warn("微信回调code为空");
            return ReturnVO.error(ReturnStatusEnum.FAIL_PARAM_EMPTY);
        }
        String token = weChatLoginService.weChatLoginBack(wxCode);
        Map<String,String> resultMap=new HashMap<>();
        resultMap.put("token",token);
        //操作成功响应系统自带的token
        return ReturnVO.ok(resultMap);
    }


}
